<?php

class m_rights_actions_AjaxChangeRightsAction extends m_backoffice_extends_Action
{
	public function execute()
	{
		$groupId = $this->getRequestParameter("groupId");
		$right = $this->getRequestParameter("right");
		
		$module = $this->getRequestParameter("rightModule");
		$bool = $this->getRequestParameter("bool");
		
		$rightsService = m_rights_services_RightsService::getInstance();
		$group = $this->getDocumentProvider()->getByUniqueId($groupId);
		
		if($rightsService->isInheritSuGroup($group))
		{
			return "true";
		}
		
		$groupRight = $rightsService->getRightsFromGroup($group);
		
		//To change the all group right
		if(!empty($module) && !empty($bool))
		{
			$rights = array();
			$moduleRights = $rightsService->readRightsFromModule($module);
			$inheritRights = $rightsService->getInheritRightsForGroup($group);
			for($i=0;$i<count($moduleRights);$i++)
			{
				if(!in_array($module."_".$moduleRights[$i]['name'], $inheritRights))
				{
					$rights[] = $module."_".$moduleRights[$i]['name'];
				}
			}
			
			switch($bool)
			{
				default:
					throw new Exception("Parameter given is wrong!");
				break;
				
				case "true":
					foreach($rights as $right)
					{
						if(!in_array($right, $groupRight))
						{
							$groupRight[] = $right;
						}
					}
					
					$return = "true";
				break;
				
				case "mid":
					foreach($rights as $right)
					{
						if(in_array($right, $groupRight))
						{
							unset($groupRight[array_search($right, $groupRight)]);
						}
						else
						{
							$groupRight[] = $right;
						}
					}
					$return = "mid";
				break;
				
				case "false":
					foreach($rights as $right)
					{
						unset($groupRight[array_search($right, $groupRight)]);
					}
					
					$return = "false";
				break;
			}
		}
		//to change one right
		else
		{	
			if(in_array($right, $groupRight))
			{
				unset($groupRight[array_search($right, $groupRight)]);
				$return = "false";
			}
			else
			{
				$groupRight[] = $right;
				$return = "true";
			}
		}
		
		$rightsService->saveRightsForGroup($group, $groupRight);
		
		return $return;
	}	
	
	public function validate()
	{
		return $this->getUserContext()->hasRight(array("backoffice_accessBo","rights_Edit"));
	}
}